package com.hdax.ssm.controller;

import com.hdax.ssm.dao.PermissionDao;
import com.hdax.ssm.dao.RolePermissionDao;
import com.hdax.ssm.dao.UserInfoDao;

import com.hdax.ssm.dao.UserRoleDao;
import com.hdax.ssm.entity.Permission;
import com.hdax.ssm.entity.Role;
import com.hdax.ssm.entity.UserInfo;
import com.hdax.ssm.service.RoleService;
import com.hdax.ssm.service.UserInfoService;
import com.hdax.ssm.service.UserRoleService;
import com.hdax.ssm.utils.MD5Utils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class UserInfoController {
    @Autowired
    private UserInfoDao userInfoDao;
    @Autowired
    private UserRoleDao userRoleDao;
    @Autowired
    private RolePermissionDao rolePermissionDao;
    @Autowired
    private PermissionDao permissionDao;

    @Resource
    private UserInfoService userInfoService;
    @Resource
    private UserRoleService userRoleService;
    @Resource
    private RoleService roleService;

    @RequestMapping("/logout")
    public String logout(HttpServletRequest request){
        request.getSession().removeAttribute("userInfo");
        return "redirect:login.jsp";
    }
    @RequestMapping("/login")
    public String login(String username,String pwd,HttpServletRequest request){
        try{
            //认证
            Subject subject = SecurityUtils.getSubject();
            UsernamePasswordToken token = new UsernamePasswordToken(username,pwd);
            subject.login(token);
            UserInfo userInfo = userInfoDao.getUser(username);
            request.getSession().setAttribute("userInfo",userInfo);
            //授权
//            if(subject.isAuthenticated()){
//                //基于角色权限控制
//                subject.hasRole("admin");
//            }
            Long roleId = userRoleDao.getRoleByUserId(userInfo.getId());
            if (null!=roleId){
                Long state = userInfo.getState();
                if(state==1){
                    request.getSession().setAttribute("msg", "用户已禁用！");
                    return "redirect:/login.jsp" ;
                }else {
                    List<Long> ids= rolePermissionDao.getRolePermissionByRoleId(roleId);
                    List<Permission> psAll = permissionDao.getPermissionByIds(ids);
                    List<Permission> psRoot = new ArrayList<>();
                    for (Permission p : psAll) {
                        if(p.getParentid()==0){
                            psRoot.add(p);
                        }
                    }
                    request.getSession().getServletContext().setAttribute("psAll",psAll);
                    request.getSession().getServletContext().setAttribute("psRoot",psRoot);
                    return "redirect:home.jsp";
                }
            }else {
                request.getSession().setAttribute("msg","没有角色");
                return "redirect:/login.jsp" ;
            }
        }catch (UnknownAccountException e){
            request.getSession().getServletContext().setAttribute("msg","用户名不存在");
        }catch (IncorrectCredentialsException e){
            request.getSession().getServletContext().setAttribute("msg","密码错误");
        }
        return "redirect:/login.jsp" ;
    }
    @RequestMapping("/getUser")
    @ResponseBody
    public Map<String,Object> getUserAll(int offset,int limit){
        return userInfoService.getUserAll(offset,limit);
    }
    @RequestMapping("/tofenpei")
    @ResponseBody
    public List<Role> tofenpei(int id){
       List<Role> roles = roleService.getAllRole();
       long roleId= userRoleService.getRoleByUserId(id);
        for (Role role :roles) {
            if(role.getId()==roleId){
                role.setIschecked(true);
            }
        }
        return roles;
    }
    @RequestMapping("/dofenpei")
    @ResponseBody
    public void dofenpei(long userId,long roleId){
        userRoleService.updateUserRole(userId,roleId);
    }

    @RequestMapping("/addUser")
    @ResponseBody
    public Map<String,Object> saveUser(UserInfo userInfo,Integer offset,Integer limit){
       return   userInfoService.saveUser(userInfo, offset, limit);
    }
    @RequestMapping("/dodel")
    @ResponseBody
    public Map<String,Object> dodel(String ids ,Integer offset,Integer limit){
        return   userInfoService.delUser(ids, offset, limit);
    }
    @RequestMapping("/update")
    @ResponseBody
    public Map<String,Object> update(UserInfo userInfo,Integer offset,Integer limit){
        return   userInfoService.update(userInfo, offset, limit);
    }

    @RequestMapping("/toupdate")
    @ResponseBody
    public UserInfo toupdate(long id){
        return   userInfoService.getUserById(id);
    }


//    @ExceptionHandler(value = {RuntimeException.class})
//    public String handlerException(RuntimeException e, HttpServletRequest req){
//        req.setAttribute("e",e.getMessage());
//        return "error";
//    }

}
